package rad.framework.mda.jpagen.actions;

import rad.framework.mda.generator.Console;
import rad.framework.mda.util.ModelUtil;

import org.eclipse.emf.common.util.EList;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.uml2.uml.Class;
import org.eclipse.uml2.uml.Element;
import org.eclipse.uml2.uml.NamedElement;
import org.eclipse.uml2.uml.Property;
import org.eclipse.uml2.uml.Stereotype;

/**
 * @author boudyacho
 * 
 */
public class AddCascadeDeleteOrphanActionExtension extends
		BaseUtiltiyActionExtension {

	protected static final String CASCADE = "org.hibernate.annotations.Cascade";

	protected static final String DELETE_ORPHAN = "{org.hibernate.annotations.CascadeType.DELETE_ORPHAN}";

	protected static final String O2M = "javax.persistence.OneToMany";

	public void fillContextMenu(IMenuManager aMenu) {
		getSubMenu(aMenu).add(new AddCascadeDeleteOrphanAction());
	}

	protected void execute(Class clazz) {
		EList<NamedElement> list = clazz.getMembers();
		for (NamedElement namedElement : list) {
			if (namedElement instanceof Property) {
				execute((Property) namedElement);
			}
		}
	}

	protected void execute(Property property) {
		if (ModelUtil.isStereotypeApplied(property, O2M)
				&& !ModelUtil.isStereotypeApplied(property, CASCADE)) {
			addCascade(property);
			Console.getStream().println(
					"Added Cascade Delete Orphan - "
							+ property.getQualifiedName());
		}
	}

	protected void addCascade(Element element) {
		Stereotype stereotype = (Stereotype) ModelUtil.getProfileElement(
				element, CASCADE);
		if (stereotype != null) {
			element.applyStereotype(stereotype);
			element.setValue(stereotype, "value", DELETE_ORPHAN);
		}
	}

	private class AddCascadeDeleteOrphanAction extends BaseUtilityAction {
		private static final String LABEL = "Add Cascade Delete Orphan Stereotypes";

		public AddCascadeDeleteOrphanAction() {
			super(LABEL);
		}
	}
}
